package com.weixin.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;

import com.google.gson.Gson;
import com.weixin.entity.HouseGoods;
import com.weixin.entity.Storehouse;
import com.weixin.service.IHouseGoodsService;
import com.weixin.service.IStorehouseService;
import com.weixin.service.impl.HouseGoodsServiceImpl;
import com.weixin.service.impl.StorehouseServiceImpl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;


@WebServlet("/HouseGoodsServlet/*")
public class HouseGoodsServlet extends HttpServlet {
	 private static Logger logger = Logger.getLogger(HouseGoodsServlet.class);
	IHouseGoodsService housegoodsService=new HouseGoodsServiceImpl();
	IStorehouseService storehouseService=new StorehouseServiceImpl();
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String path = request.getPathInfo().substring(1);
		if("houseGoodsList".equals(path)) {
			HouseGoodsList(request,response);
		}else if("houseGoodsSerarchList".equals(path)){
			HouseGoodsSerarchList(request,response);
		}else if("updateStorehouse".equals(path)) {
			UpdateStorehouse(request,response);
		}else if("updateNewStorehouse".equals(path)) {
			UpdateNewStorehouse(request,response);
		}else if("addRemark".equals(path)) {
			AddRemark(request,response);
		}else if("addVolume".equals(path)) {
			AddVolume(request,response);
		}else if("pictureList".equals(path)) {
			PictureList(request,response);
		}else if("outGoodsInfo".equals(path)) {
			OutGoodsInfo(request,response);
		}
	}

	private void OutGoodsInfo(HttpServletRequest request, HttpServletResponse response) {
		try {
			 double moneyTotal=0.0;
			 int volumeTotal=0;
			 List<HouseGoods> houseGoodsList = housegoodsService.getAllAboutForExcel();
			 TemplateExportParams params = new TemplateExportParams("/mould/HouseGoodsInfo.xls");
		     Map<String, Object> map = new HashMap<String, Object>();
		     map.put("date",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		     List<Map<String, String>> listMap = new ArrayList<Map<String, String>>();
		     for (HouseGoods housegoods : houseGoodsList) {
		        	Map<String, String> lm = new HashMap<String, String>();
		            lm.put("goods_id",housegoods.getGoods_id()+"");
		            lm.put("goods_name", housegoods.getGoods_name());
		            lm.put("number",housegoods.getNumber()+"");
		            lm.put("unit", housegoods.getUnit());
		            if(housegoods.getSum()!=null) {
		            	lm.put("sum",housegoods.getSum()+"元");
		            	moneyTotal=moneyTotal+housegoods.getSum();//得到总金额		            	
		            }else {
		            	lm.put("sum","0");
		            }
		            lm.put("volume",housegoods.getVolume()+"立方米");
		            volumeTotal=volumeTotal+housegoods.getVolume();//得到总体积
		            lm.put("storehouse_name",housegoods.getStorehouse_name());
		            
		            if(housegoods.getRemark()!=null) {
		            	lm.put("remark",housegoods.getRemark());
		            }else {
		            	lm.put("remark","无");
		            }		            
		            listMap.add(lm);
			}
		      map.put("maplist", listMap);
		      map.put("moneyTotal", moneyTotal+"元");
		      map.put("volumeTotal", volumeTotal+"立方米");

		      Workbook workbook = ExcelExportUtil.exportExcel(params, map);
//		      File savefile = new File("D:/excel/");
//		      if (!savefile.exists()) {
//		            savefile.mkdirs();
//		      }
		      FileOutputStream fos = new FileOutputStream("D:/HouseGoodsInfo.xls");
		      workbook.write(fos);
		      fos.close();
		      logger.error("导出库存商品表");
		      response.getWriter().print(1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e);
		}
	}

	private void PictureList(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<HouseGoods> houseGoodsList = housegoodsService.getAllForPicture();
			request.setAttribute("housegoodsList",houseGoodsList);
			request.getRequestDispatcher("/page/user/goodsManage/goodsPictureList.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void AddVolume(HttpServletRequest request, HttpServletResponse response) {
		int houseGoodsId =Integer.valueOf(request.getParameter("h_goods_id"));
		int volume =Integer.valueOf(request.getParameter("volume"));
		System.out.println("体积是："+volume);
		try {
			HouseGoods houseGoods = housegoodsService.selectById(houseGoodsId);
			houseGoods.setVolume(volume);
			if(housegoodsService.updateHGoods(houseGoods)) {
				logger.error("更改体积，h_goods_id="+houseGoodsId+"volume"+volume);
				response.getWriter().print(1);
			}else {
				response.getWriter().print(0);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void AddRemark(HttpServletRequest request, HttpServletResponse response) {
		int houseGoodsId =Integer.valueOf(request.getParameter("h_goods_id"));
		String remark = request.getParameter("remark");
		
		try {
			HouseGoods houseGoods = housegoodsService.selectById(houseGoodsId);
			houseGoods.setRemark(remark);
			if(housegoodsService.updateHGoods(houseGoods)) {
				logger.error("更改备注，h_goods_id="+houseGoodsId+"remark"+remark);
				response.getWriter().print(1);
			}else {
				response.getWriter().print(0);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void UpdateNewStorehouse(HttpServletRequest request, HttpServletResponse response) {
		int goodsid =Integer.valueOf(request.getParameter("goodsId"));
		int storehouseId= Integer.valueOf(request.getParameter("storehouseId"));
		try {
			HouseGoods houseGoodsList = housegoodsService.selectById(goodsid);
			houseGoodsList.setStorehouse_id(storehouseId);
			if(housegoodsService.updateHGoods(houseGoodsList)) {
				logger.error("更改仓库，goodsid="+goodsid+"storehouseId"+storehouseId);
				response.getWriter().print(1);
			}else {
				response.getWriter().print(0);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void UpdateStorehouse(HttpServletRequest request, HttpServletResponse response) {
		String h_goods_id = request.getParameter("h_goods_id");	
		//System.out.println("准备要更改了哈，编号是："+h_goods_id);
		try {
			List<Storehouse> storehouseList = storehouseService.selectAll();
			request.setAttribute("storehouseList",storehouseList);
			request.setAttribute("goodsId",h_goods_id);
			request.getRequestDispatcher("/page/user/goodsManage/updateStorehouseForGoods.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}

	private void HouseGoodsSerarchList(HttpServletRequest request, HttpServletResponse response) {
		int pageSize=Integer.valueOf(request.getParameter("pageSize"));
		int pageNum=Integer.valueOf(request.getParameter("pageNum"));
		String search = request.getParameter("search");
		try {
			//表格数据
			List<HouseGoods> houseGoodsList = housegoodsService.getSearchAbout(pageSize, pageNum, search);
			//计算总页数
			
			double pageCount=Math.ceil(housegoodsService.getSearchAboutTotal(search)*1.0/pageSize);
			System.out.println("总数据条数："+housegoodsService.getSearchAboutTotal(search));
			System.out.println("pageCount:"+pageCount+"/"+"pageSize:"+pageSize);
			Map<String,Object> map=new HashMap<>();
			map.put("houseGoodsList", houseGoodsList);
			map.put("pageNum", pageNum);
			map.put("pageCount",pageCount);
			response.getWriter().print(new Gson().toJson(map));			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void HouseGoodsList(HttpServletRequest request, HttpServletResponse response) {
		int pageSize=Integer.valueOf(request.getParameter("pageSize"));
		int pageNum=Integer.valueOf(request.getParameter("pageNum"));
		try {
			//表格数据
			List<HouseGoods> houseGoodsList = housegoodsService.getAllAbout(pageSize,pageNum);
			//计算总页数
			double pageCount=Math.ceil(housegoodsService.getAllAboutTotal()*1.0/pageSize);
			System.out.println("总数据条数："+housegoodsService.getAllAboutTotal());
			System.out.println("pageCount:"+pageCount+"/"+"pageSize:"+pageSize);
			Map<String,Object> map=new HashMap<>();
			map.put("houseGoodsList", houseGoodsList);
			map.put("pageNum", pageNum);
			map.put("pageCount",pageCount);
			response.getWriter().print(new Gson().toJson(map));			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
